// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// t [author] rhyme_lph
// Y [email]  rhymelph@gmail.com
// N [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/current_subscription_entity.dart';
import 'package:finance_app/src/page/dashboard/dashboard_drawer_view.dart';
import 'package:finance_app/src/page/dashboard/dashboard_view.dart';
import 'package:finance_app/src/provider/dashboard_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/button/assistant_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/common/subscription_due_banner.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart' hide SliverAppBar;
import 'package:flutter/material.dart' hide NestedScrollView;

import 'dashboard/dashboard_staff_view.dart';

@RouterMeta(paramName: "dashboardPage")
class DashboardPage extends StatefulWidget {
  @override
  _DashboardPageState createState() => _DashboardPageState();
}

class _DashboardPageState extends State<DashboardPage> with PagePresenter<DashboardPage, DashboardProvider> {
  @override
  void initState() {
    RProvider.myProvider.globalMap[ConfigKey.showLogin] = false;
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        titleWidget: rootListBuilder<String>(
            builder: (BuildContext context, String value, Widget child) => value.isEmpty ? Container() : _buildCompanySelectWidget(value),
            selector: (_, __) => Config.currentCompany?.name ?? ''),
        automaticallyImplyLeading: true,
        actions: [
          AssistantButton(iconKey: provider.assistantKey),
          rootListBuilder(
            selector: (_, __) => Config.hasPermission(PermissionUtils.homeDashboard),
            builder: (BuildContext context, bool value, Widget child) => value
                ? Container()
                : listBuilder<List<String>>(
                    selector: (_, __) => List.from(__.getChildProvider<HrAndPayrollProvider>().menuList),
                    builder: (BuildContext context, List<String> value, Widget child) => value.length > 0
                        ? NormalMorePopupButton(
                            horizontalPadding: getDp(15),
                            onSelect: provider.getChildProvider<HrAndPayrollProvider>().onSelectMenu,
                            menuList: value,
                          )
                        : Container(),
                  ),
          ),
        ],
        leading: IconButton(
            icon: Icon(
              Icons.menu,
              key: provider.drawerKey,
            ),
            onPressed: () {
              scaffoldKey.currentState.openDrawer();
            }),
      );

  Widget _buildCompanySelectWidget(String value) {
    return PressedOpacityButton(
        onPressed: provider.onChangeCompany,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                constraints: BoxConstraints(
                  maxWidth: getDp(190),
                ),
                child: Text(value)),
            SizedBox(
              width: getDp(10),
            ),
            Image.asset(
              A.assetsImagesStyleArrow,
              width: getDp(12),
              height: getDp(9),
            ),
          ],
        ));
  }

  @override
  Widget get drawer => DashboardDrawerView();

  @override
  Widget get buildWidget => rootListBuilder<bool>(
      selector: (_, __) => Config.hasPermission(PermissionUtils.homeDashboard),
      builder: (BuildContext context, bool value, Widget child) => Stack(
            children: [
              Config.token != null // prevent app to rebuild when logging out
                  ? value
                      ? DashboardView()
                      : DashboardStaffView()
                  : Container(),
              _buildTop(),
            ],
          ));

  Widget _buildTop() => rootListBuilder<CurrentSubscriptionEntity>(
      selector: (_, __) => Config.currentSubscription,
      builder: (BuildContext context, CurrentSubscriptionEntity value, Widget child) => Positioned(
            top: 0.0,
            left: 0.0,
            right: 0.0,
            child: (value?.messages?.where((element) => element.type == 'alert')?.length ?? 0) > 0
                ? Container(
                    decoration: BoxDecoration(
                      color: aceLightBlue,
                    ),
                    child: Column(
                        children: value.messages
                            .map(
                              (e) => PressedOpacityButton(onPressed: provider.onNavSub, child: SubscriptionDueBanner(message: e.info)),
                            )
                            .toList()),
                  )
                : Container(),
          ));
}
